package cn.shyouchi.wuguanjia.android.api.profile;

import android.content.Context;

import java.io.File;
import java.util.Map;

import cn.shyouchi.wuguanjia.android.api.ClientProvider;
import cn.shyouchi.wuguanjia.android.api.UserStorageProvider;
import cn.shyouchi.wuguanjia.android.components.storage.UserStorage;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.functions.Func1;
import top.zibin.luban.Luban;

/**
 * Created by Eenie on 2017/3/9 at 15:47
 * Email: 472279981@qq.com
 * Des:
 */

public class ProfileApi {

    ProfileService mService;
    Context mContext;

    public ProfileApi(Context context) {
        this.mContext = context;
        UserStorage mUserStorage = UserStorageProvider.Default();
        mService = ClientProvider.getDefaultClient().getRetrofit(mUserStorage).create(ProfileService.class);
    }


    public Observable<BaseRequestResult> upProfile(Map<String, Object> params) {
        return mService.upProfile(params);
    }


    public Observable<BaseRequestResult> upHeader(String headImg) {
            File file = new File(headImg);
            return Luban.get(mContext)
                    .load(file)
                    .putGear(Luban.THIRD_GEAR)
                    .asObservable()
                    .flatMap(new Func1<File, Observable<BaseRequestResult>>() {
                        @Override
                        public Observable<BaseRequestResult> call(File file) {
                            MultipartBody.Part body;
                            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                            body = MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);
                            return mService.upHeader(body);
                        }
                    });
    }


}
